package com.seatiger.structure.trie;

import java.util.TreeMap;

/**
 * 字典树的定义，用于字符串的检索
 */
public class Trie {
    private class Node {
        private boolean isWord;
        //下一个节点的表示
        private TreeMap<Character, Node> next;

        public Node(boolean isWord) {
            this.isWord = isWord;
            this.next = new TreeMap<>();
        }

        public Node() {
            this(false);
        }
    }

    private Node root;
    private int size;

    public int getSize() {
        return size;
    }

    public Trie() {
        this.root = new Node();
        this.size = 0;
    }

    /**
     * 向trie中添加单词
     *
     * @param word
     */
    public void add(String word) {
        Node cur = root;
        //将每个节点插入trie中
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            //检查一下当前节点的下一个节点中是否包含这个字符
            //如果不包含，插入
            if (cur.next.get(c) == null) {
                cur.next.put(c, new Node());
            }
            cur = cur.next.get(c);
        }
        if (!cur.isWord) {
            //最后一个单词的末尾，设置标志
            cur.isWord = true;
            size++;
        }
    }

    /**
     * 判断是否包含某个单词
     * @param word
     * @return
     */
    public boolean contains(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c) == null) {
                return false;
            }
            cur = cur.next.get(c);
        }
        return cur.isWord;
    }

    /**
     * 查询是否在Trie中有单词以prefix为前缀
     * @param prefix
     * @return
     */
    public boolean isPrefix(String prefix) {
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (cur.next.get(c) == null) {
                return false;
            }
            cur = cur.next.get(c);
        }
        return true;
    }
}
